package gridsoft.sapi.config;

import org.noear.solon.annotation.Component;
import org.noear.solon.core.exception.StatusException;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Filter;
import org.noear.solon.core.handle.FilterChain;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component
public class AppFilter implements Filter { //如果想排除静态资源，可以换成 RouterInterceptor
    static final Logger log = LoggerFactory.getLogger(AppFilter.class);

    @Override
    public void doFilter(Context ctx, FilterChain chain) throws Throwable {
        try{
            chain.doFilter(ctx);
        } catch (StatusException e) {
            if (e.getCode() == 404){
                ctx.render(Result.failure(404, "资源不存在"));
            } else if (e.getCode() == 405){
                ctx.render(Result.failure(405, "资源方式不支持"));
            } else if (e.getCode() == 400){
                ctx.render(Result.failure(400, "请求格式或参数有问题"));
            } else if (e.getCode() == 500){
                ctx.render(Result.failure(500, e.getMessage()));
            }
        } catch (Throwable e) {
            ctx.status(500);
            log.error("500 ERROR: ", e);
            ctx.render(Result.failure(500, "服务端运行出错", e.getMessage()));
        }
    }
}
